import sys,os
import pyfaidx


def format_seq(seq, wrap):
    seq = seq.upper()
    chunks = [seq[i:i+wrap] for i in range(0, len(seq), wrap)]
    return "\n".join(chunks) + "\n"




out = open(sys.argv[2], "w")
chromnum = int(sys.argv[3])
speprefix = sys.argv[4]
dic = {}
name = 1



fasta = pyfaidx.Fasta(sys.argv[1])

chrlist = fasta.keys()
lengthlist = []
for i in chrlist:
    length = fasta[i][0:].end
    dic[length] = i
    lengthlist.append(length)
lengthlist.sort(reverse=True)

index = 1
for i in lengthlist:
    seq = str(fasta[dic[i]][0:].seq)
    seq = format_seq(seq, 80)
    if i <= 1:
        continue
    else:
        if index < 10 and index <= chromnum:
            out.write(f">{speprefix}Chr0{index}\n{seq}")
        elif index < 10 and index > chromnum:
            out.write(f">{speprefix}Scaffold0{index}\n{seq}")
        elif index >= 10 and index <= chromnum:
            out.write(f">{speprefix}Chr{index}\n{seq}")
        else:
             out.write(f">{speprefix}Scaffold{index}\n{seq}")
    index += 1

out.close()
        
        

